package com.wt.struggle.goodbye.sq.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Message
import android.support.design.widget.TabLayout
import android.support.v4.app.ActivityCompat
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.gson.reflect.TypeToken
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ItemClickListener
import com.wt.struggle.goodbye.base.ProV4Fragment
import com.wt.struggle.goodbye.base.Send
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.wt.struggle.goodbye.sq.activity.PickDetailsActivity
import com.wt.struggle.goodbye.sq.adapter.HandPickAdapter
import com.wt.struggle.goodbye.view.AddCommentPop
import kotlinx.android.synthetic.main.sq_fragment_layout.*

class SqFragment : ProV4Fragment() {
    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            Send.MY_NEWS_CODE -> {

                removeLoadDialog()
                sheQuRefreshView.isRefreshing = false

                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult
                    if (result != null && result != "" && result != "null") {
                        val arr: ArrayList<NewsInfo> =
                            gson!!.fromJson(result, object : TypeToken<ArrayList<NewsInfo>>() {}.type)

                        if (arr.size != 0) {
                            page++
                            if (isLoad) {
                                adapter.updateData(arr)
                            } else {
                                adapter.updateDataClear(arr)
                            }
                        } else {
                            showToastShort(activity!!, "无更多数据")
                        }

                    } else {
                        showToastShort(activity!!, "暂无数据")
                    }
                }
            }

            Send.COLLECT_CODE -> {
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort(activity!!, "操作成功")
                    adapter.change(clickPosition)
                }

            }

            Send.ADD_COMMENT -> {
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort(activity!!, "评论成功")
                    setAlpha(activity!!, 1f)
                    addPop!!.dismiss()
                }
            }
        }
    }

    override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.sq_fragment_layout, container, false)

    }


    var sheQuResult = ""

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        initAdapter()

        getLocation()

        if (sheQuResult != "") {
            val arr: ArrayList<NewsInfo> =
                gson!!.fromJson(sheQuResult, object : TypeToken<ArrayList<NewsInfo>>() {}.type)
            adapter.updateData(arr)

        } else {
            getList()
        }


        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                when (tab!!.position) {
                    0 -> {
                        isCode = 0
                    }
                    1 -> {
                        isCode = 1
                    }
                }

                getList()
            }

        })

        checkBoxSearch.setOnCheckedChangeListener { compoundButton, b ->
            if (b) {
                editLinear.visibility = View.VISIBLE
            } else {
                editLinear.visibility = View.GONE
                hideInPut(etEditText)
            }
        }

        buttonSure.setOnClickListener {

            keyWord = etEditText.text.toString()
            page = 1
            isLoad = false

            getList()

            keyWord = ""
            editLinear.visibility = View.GONE
            checkBoxSearch.isChecked = false

        }

        sheQuRefreshView.setOnRefreshListener {
            isLoad = false
            page = 1
            getList()
        }

        sheQuRefreshView.onLoadMore(handPickRecyclerView) {
            isLoad = true
            getList()
        }

    }

    var page = 1
    var isCode = 0
    var keyWord = ""

    var isLoad = false

    private fun getList() {
        send!!.getSQList(page, isCode, keyWord, handler)
        showLoadDialog(activity!!)
    }


    lateinit var adapter: HandPickAdapter
    val list = arrayListOf<NewsInfo>()

    var clickPosition: Int = 0


    private fun initAdapter() {

        handPickRecyclerView.layoutManager = LinearLayoutManager(activity)
        handPickRecyclerView.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
        adapter = HandPickAdapter(activity!!, list)
        handPickRecyclerView.adapter = adapter

        adapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {
                val intent = Intent(activity!!, PickDetailsActivity::class.java)
                intent.putExtra("info", list[position])
                startActivity(intent)

            }

            override fun onLongClick(position: Int) {

            }

        }

        adapter.collectOrComment = object : HandPickAdapter.OnCollectOrCommentListener {
            override fun onCollect(position: Int) {

                this@SqFragment.clickPosition = position
                send!!.collect(list[position].id.toString(), 2, handler)
                showLoadDialog(activity!!, "收藏中")
            }


            override fun onComment(position: Int) {

                this@SqFragment.clickPosition = position
                showAdd()

            }

        }
    }

    var addPop: AddCommentPop? = null

    fun showAdd() {
        addPop = AddCommentPop(activity!!)
        setAlpha(activity!!, 0.6f)
        addPop!!.show(object : AddCommentPop.OnAddBackListener {
            override fun onBack(content: String) {
                addComment(content)
            }
        })

        addPop!!.setOnDismissListener {
            setAlpha(activity!!, 1f)
            addPop!!.dismiss()
        }
    }

    /**
     * 添加评论
     */
    private fun addComment(content: String) {
        val info = list[clickPosition]
        val userInfo = ProUserInfo()
        userInfo.contentId = info.id!!
        userInfo.commentID = 0
        userInfo.content = content
        userInfo.lat = location!!.latitude.toString()
        userInfo.lng = location!!.longitude.toString()
        userInfo.location = addressStr

        send!!.addComment(userInfo, handler)
        showLoadDialog(activity!!)


    }


    /**
     * 获取位置服务
     */
    private fun getLocation() {
        val code = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.ACCESS_FINE_LOCATION)
        val code2 = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.ACCESS_COARSE_LOCATION)

        if (code == PackageManager.PERMISSION_GRANTED && code2 == PackageManager.PERMISSION_GRANTED) {

            get()

        } else {

            ActivityCompat.requestPermissions(
                activity!!,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
                5678
            )
        }

    }


    var location: Location? = null
    var addressStr: String = ""

    @SuppressLint("MissingPermission")
    fun get() {
        val locationManager = activity!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val locationProvider = LocationManager.NETWORK_PROVIDER

        // 获取Location
        location = locationManager.getLastKnownLocation(locationProvider)

        // 监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 5000, 1f, object : LocationListener {
            override fun onLocationChanged(p0: Location?) {
                this@SqFragment.location = p0

                val geocoder = Geocoder(activity!!)

                val arr = geocoder.getFromLocation(location!!.latitude, location!!.longitude, 1);

                val address = arr[0]
                addressStr = address.featureName

            }

            override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {

            }

            override fun onProviderEnabled(p0: String?) {

            }

            override fun onProviderDisabled(p0: String?) {

            }

        })


    }
}